package com.baida.retail.tasksystem.service.impl;

import com.baida.retail.tasksystem.config.CommonServiceConfig;
import com.baida.retail.tasksystem.service.CommonService;
import com.baida.retail.tasksystem.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by eric on 2020/4/17.
 */
@Service
public class CommonServiceImpl implements CommonService {

    private static final Logger logger = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Autowired
    private CommonServiceConfig commonServiceConfig;


    @Override
    public String sendSms(String phoneNum, String templateCode, Map<String, String> params) throws IOException {
        params.put("mid", String.valueOf(commonServiceConfig.getMid()));
        params.put("templateCode", templateCode);
        params.put("phoneNum", phoneNum);
        return sendRequestToCommonServer(params, commonServiceConfig.getKeyForMid(), smsUrl());
    }


    private String sendRequestToCommonServer(Map<String, String> params, String key, String url) throws IOException {
        String signContent = StringUtils.buildConnectedParamsWithKeySorted(params) + key;
        String sign = DigestUtils.md5Hex(signContent).toLowerCase();
        params.put("sign", sign);
        String bodyString = StringUtils.buildConnectedParamsWithKeySorted(params);
        String result = Request.Post(url)
                .bodyString(
                        bodyString,
                        ContentType.APPLICATION_FORM_URLENCODED.withCharset("utf-8"))
                .execute().returnContent().asString();
        logger.info("common server response: {}", result);
        return result;
    }


    private String smsUrl() {
        return commonServiceConfig.getServerUrl() + "/common-server/sms/aliyun/send";
    }
}
